<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot-scope="{row}" slot="taxRate">
        {{row.taxRate}}%
      </template>
      <template slot-scope="{row}" slot="productDiscount">
        {{row.productDiscount}}%
      </template>
      <template  slot="taxRateForm" slot-scope="{type}">
        <div style="display:flex">
          <input type="number" v-model="form.taxRate" :disabled="type=='view'" class="el-input__inner" style="height:32px;line-height:32px;" :style="type=='view'?'padding-left:0;':''" placeholder="请输入 税率（百分数）"><span>%</span>
        </div>
      </template>
      <template  slot="productDiscountForm" slot-scope="{type}">
        <div style="display:flex">
          <input type="number" v-model="form.productDiscount" :disabled="type=='view'" class="el-input__inner" style="height:32px;line-height:32px;" :style="type=='view'?'padding-left:0;':''" placeholder="请输入 折扣（百分数）"><span>%</span>
        </div>
      </template>
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.product_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove , getBrandProductDetail} from "@/api/merchant/product";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        defaultAdvanceId:"",
        defaultAcctName:"",
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          border: true,
          viewBtn: true,
          dialogClickModal: false,
          align:"center",
          labelWidth:150,
          column: [
            {
              label: "id",
              prop: "id",
              display:false,
            },
            {
              label: "品牌",
              prop: "brandId",
              type:"select",
              hide:true,
              editDisplay:false,
              viewDisplay:false,
              filterable:true,
              search:true,
              dicUrl:"/api/merchant-bmg/brand/list?current=1&size=100&brandStatus=OPEN",
              dicMethod:'get',
              props:{
                label:"brandName",
                value:"id",
                res:"data.records"
              },
              cascaderItem:["brandProductId"],
              rules: [{
                required: true,
                message: "请输入品牌",
                trigger: "blur"
              }]
            },
            {
              label: "品牌名称",
              prop: "brandName",
              addDisplay:false,
              editDisplay:true,
              editDisabled:true,
              rules: [{
                required: true,
                message: "请输入品牌名称",
                trigger: "blur"
              }]
            },
            {
              label: "商品",
              prop: "brandProductId",
              type:"select",
              hide:true,
              search:true,
              editDisplay:false,
              viewDisplay:false,
              filterable:true,
              dicUrl:`/api/merchant-bmg/brandproduct/list?current=1&size=100&productStatus=OPEN&brandId={{key}}`,
              dicMethod:'get',
              props:{
                label:"productName",
                value:"id",
                res:"data.records"
              },
              rules: [{
                required: true,
                message: "请输入商品",
                trigger: "blur"
              }],
              change:this.brandProductChange
            },
            {
              label: "商品名称",
              prop: "brandProductName",
              addDisplay:false,
              editDisplay:true,
              editDisabled:true,
              minWidth:100,
              rules: [{
                required: true,
                message: "请输入商品名称",
                trigger: "blur"
              }]
            },
            {
              label: "商户",
              prop: "merchantId",
              type:"select",
              hide:true,
              search:true,
              //editDisplay:false,
              editDisabled:true,
              viewDisplay:false,
              filterable:true,
              dicUrl:"/api/merchant-bmg/merchant/list?current=1&size=100&merchantStatus=OPEN",
              dicMethod:'get',
              props:{
                label:"merchantName",
                value:"id",
                res:"data.records"
              },
              cascaderItem:["advanceId"],
              rules: [{
                required: true,
                message: "请输入商户",
                trigger: "blur"
              }]
            },
            {
              label: "商户别名",
              prop: "merchantAlias",
              display:false,
              hide:true,
              rules: [{
                required: true,
                message: "请输入商户别名",
                trigger: "blur"
              }]
            },
            {
              label: "商户名称",
              prop: "merchantName",
              addDisplay:false,
              editDisplay:true,
              editDisabled:true,
              rules: [{
                required: true,
                message: "请输入商户名称",
                trigger: "blur"
              }]
            },
            {
              label: "商户商品名称",
              prop: "productName",
              minWidth:100,
              rules: [{
                required: true,
                message: "请输入商品名称",
                trigger: "blur"
              }]
            },
            {
              label: "商户侧编码",
              prop: "productNo",
              minWidth:90,
              hide:true,
            },
            {
              label: "面值",
              prop: "faceValue",
              type:"number",
              precision:2,
              minRows:0,
              disabled:true,
              // change:this.faceValueChange,
            },
            {
              label: "市场价",
              prop: "marketPrice",
              type:"number",
              hide:true,
              precision:2,
              minRows:0,
              rules: [{
                required: true,
                message: "请输入市场价",
                trigger: "blur"
              }]
            },
            {
              label: "采购成本",
              prop: "costValue",
              type:"number",
              hide:true,
              precision:2,
              minRows:0,
              // change:this.costValueChange,
              rules: [{
                required: true,
                message: "请输入采购成本",
                trigger: "blur"
              }]
            },
            {
              label: "收货账户",
              prop: "recvAcctType",
              display:false,
              hide:true,
              rules: [{
                required: true,
                message: "请选择收货账户类型",
                trigger: "blur"
              }]
            },
            {
              type:"select",
              label: "收货账户类型",
              minWidth:100,
              prop: "recvAcctTypeName",
              dicUrl:"/api/merchant-bmg/receiveaccounttype/list",
              dicMethod:'get',
              props:{
                label:"name",
                value:"id",
                res:"data.records"
              },
              rules: [{
                required: true,
                message: "请选择收货账户类型",
                trigger: "blur"
              }]
            },
            {
              label: "商品折扣",
              prop: "productDiscount",
              hide:true,
              // disabled:true,
              rules: [{
                required: true,
                message: "请输入折扣",
                trigger: "blur"
              }]
            },
            {
              type:"select",
              label: "发货方式",
              prop: "shipMode",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=MERCHANT_SHIP_MODE",
              dicMethod:'get',
              props:{
                label:"dictValue",
                value:"dictKey"
              },
              rules: [{
                required: true,
                message: "请选择发货方式",
                trigger: "blur"
              }]
            },
            {
              type:"select",
              label: "库存类型",
              prop: "inventoryType",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=MERCHANT_INVENTORY_TYPE",
              dicMethod:'get',
              props:{
                label:"dictValue",
                value:"dictKey"
              },
              rules: [{
                required: true,
                message: "请选择库存类型",
                trigger: "blur"
              }],
              change:this.test,
            },
            // {
            //   label: "商品图片",
            //   prop: "productPicture",
            //   type:"upload",
            //   listType: 'picture-img',
            //   action:"/api/blade-resource/oss/endpoint/put-file",
            //   propsHttp:{
            //     res:"data",
            //     url:"link"
            //   },
            //   rules: [{
            //     required: true,
            //     message: "请输入商品图片",
            //     trigger: "blur"
            //   }]
            // },
            {
              type:"select",
              label: "状态",
              prop: "productStatus",
              search:true,
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=MERCHANT_PRODUCT_STATUS",
              dicMethod:'get',
              props:{
                label:"dictValue",
                value:"dictKey"
              },
              rules: [{
                required: true,
                message: "请选择状态",
                trigger: "blur"
              }]
            },
            {
              type:"select",
              label: "商户开具发票类型",
              minWidth:120,
              hide:true,
              prop: "invoiceType",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=MERCHANT_INVOICE_TYPE",
              dicMethod:'get',
              props:{
                label:"dictValue",
                value:"dictKey"
              },
              rules: [{
                required: true,
                message: "请选择商户开具发票类型",
                trigger: "blur"
              }]
            },
            {
              label: "税率",
              prop: "taxRate",
              type:"number",
              hide:true,
              precision:2,
              minRows:0,
              rules: [{
                required: true,
                message: "请输入税率",
                trigger: "blur"
              }]
            },
            {
              label: "预付款账户",
              prop: "advanceId",
              type:"select",
              dicUrl:`/api/merchant-bmg/advanceinventory/list?current=1&size=100&merchantId={{key}}`,
              dicMethod:'get',
              props:{
                label:"acctName",
                value:"id",
                res:"data.records"
              },
              minWidth:90,
              hide:true,
              display:false,
              rules: [{
                required: true,
                message: "请输入预付款账户",
                trigger: "blur"
              }]
            },
            {
              label: "预付款账户",
              prop: "acctName",
              display:false,
              minWidth:90,
              rules: [{
                required: true,
                message: "请输入使用说明",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.product_add, true),
          viewBtn: this.vaildData(this.permission.product_view, true),
          delBtn: this.vaildData(this.permission.product_delete, true),
          editBtn: this.vaildData(this.permission.product_edit, true)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        row.brandName = row.$brandId;
        row.brandProductName = row.$brandProductId;
        row.merchantName = row.$merchantId;
        row.acctName = row.$advanceId;

        row.recvAcctType = row.recvAcctTypeName;
        row.recvAcctTypeName = row.$recvAcctTypeName;

        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if(row.recvAcctTypeName != row.$recvAcctTypeName){
          row.recvAcctType = row.recvAcctTypeName;
          row.recvAcctTypeName = row.$recvAcctTypeName;
        }
        if(row.advanceId == this.defaultAcctName){
          row.advanceId = this.defaultAdvanceId
          row.acctName = this.defaultAcctName
        }else{
          row.acctName = row.$advanceId;
        }
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.defaultAdvanceId = res.data.data.advanceId
            this.defaultAcctName = res.data.data.acctName
            res.data.data.advanceId = res.data.data.acctName
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        // this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      test (row) {
        let advanceId = this.findObject(this.option.column , "advanceId");
        if(row.value == "ADVANCE_AMOUNT"){
          advanceId.display = true;
        }else{
          advanceId.display = false;
        }
      },
      brandProductChange(row){
        if(row.value){
          getBrandProductDetail(row.value).then((res)=>{
            this.form.faceValue=res.data.data.price
          })
        }
      },
      faceValueChange(row){
        if(row.value){
          if(this.form.costValue){
            this.form.productDiscount = (this.form.costValue/row.value).toFixed(2)
          }
        }
      },
      costValueChange(row){
        if(row.value){
          if(this.form.faceValue){
            this.form.productDiscount = (row.value/this.form.faceValue).toFixed(2)
          }
        }
      },
    }
  };
</script>

<style lang="scss" scoped>
:deep( input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button) {
    -webkit-appearance: none !important;
    margin: 0;
  }
:deep( input[type="number"]) {
    -moz-appearance: textfield;
  }
</style>>

